using MediatR;
using Microsoft.AspNetCore.Mvc;
using RBAC.ErrorCode;
using RBAC.Read.Api.Application.Command.DataBashboard;
using RBAC.Read.Api.Application.Dto.DataBashboard;
using RBAC.Read.Api.Application.Command.Dashboard;
using RBAC.Read.Api.Application.Dto.Dashboard;

namespace RBAC.Read.Api.Controllers
{
    /// <summary>
    /// 数据看板控制器 - 提供看板任务和产品报工的查询接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DashboardController : ControllerBase
    {
        private readonly IMediator mediator;

        public DashboardController(IMediator mediator)
        {
            this.mediator = mediator;
        }

        /// <summary>
        /// 待审批数量统计（采购单/销售单/退货/入库/出库/开票/请购）
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>各单据待审批数量与合计</returns>
        [HttpGet]
        [ProducesResponseType(typeof(APIResult<PendingApprovalCountsDto>), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<APIResult<PendingApprovalCountsDto>> GetPendingApprovalCounts(CancellationToken cancellationToken)
        {
            try
            {
                var cmd = new GetPendingApprovalCountsCommand();
                return await mediator.Send(cmd, cancellationToken);
            }
            catch (Exception ex)
            {
                return new APIResult<PendingApprovalCountsDto>
                {
                    Code = APIEnums.Error,
                    Msg = $"获取待审批统计失败: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 获取看板任务分页数据（工单执行进度看板）
        /// </summary>
        /// <param name="request">查询参数：支持工单编号、状态、产品信息、工序名称、时间范围筛选</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>分页结果，包含工单进度详情</returns>
        /// <response code="200">查询成功</response>
        /// <response code="400">参数错误</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet]
        [ProducesResponseType(typeof(APIPaging<KanbanTasksListDto>), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<APIPaging<KanbanTasksListDto>> GetKanbanTasksPage([FromQuery] GetKanbanTasksPageCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = await mediator.Send(request, cancellationToken);
                return result;
            }
            catch (Exception ex)
            {
                return new APIPaging<KanbanTasksListDto>
                {
                    Code = APIEnums.Error,
                    Msg = $"获取看板任务分页失败: {ex.Message}",
                    PageDatas = new List<KanbanTasksListDto>(),
                    TotalCount = 0
                };
            }
        }

        /// <summary>
        /// 获取产品报工分页数据（生产管控大屏-产品报工区域）
        /// </summary>
        /// <param name="request">查询参数：支持产品名称、报工时间范围、数量筛选</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>分页结果，包含产品报工详情</returns>
        /// <response code="200">查询成功</response>
        /// <response code="400">参数错误</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet]
        [ProducesResponseType(typeof(APIPaging<ProductionDashboardListDto>), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<APIPaging<ProductionDashboardListDto>> GetProductionDashboardPage([FromQuery] GetProductionDashboardPageCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = await mediator.Send(request, cancellationToken);
                return result;
            }
            catch (Exception ex)
            {
                return new APIPaging<ProductionDashboardListDto>
                {
                    Code = APIEnums.Error,
                    Msg = $"获取产品报工分页失败: {ex.Message}",
                    PageDatas = new List<ProductionDashboardListDto>(),
                    TotalCount = 0
                };
            }
        }

        /// <summary>
        /// 获取看板任务统计数据（用于大屏卡片展示）
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>统计结果：总数、各状态数量等</returns>
        /// <response code="200">查询成功</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet]
        [ProducesResponseType(typeof(APIResult<object>), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<APIResult<object>> GetKanbanTasksStatistics(CancellationToken cancellationToken)
        {
            try
            {
                // 获取所有看板任务（不分页）用于统计
                var allTasksRequest = new GetKanbanTasksPageCommand
                {
                    PageIndex = 1,
                    PageSize = int.MaxValue // 获取全部数据用于统计
                };

                var allTasksResult = await mediator.Send(allTasksRequest, cancellationToken);

                if (allTasksResult.Code != APIEnums.Success)
                {
                    return new APIResult<object>
                    {
                        Code = APIEnums.Error,
                        Msg = "获取看板任务统计失败",
                        Data = null
                    };
                }

                var tasks = allTasksResult.PageDatas ?? new List<KanbanTasksListDto>();

                var statistics = new
                {
                    TotalCount = tasks.Count,
                    StatusCounts = tasks.GroupBy(t => t.Status)
                                       .ToDictionary(g => g.Key, g => g.Count()),
                    AvgCompletionRate = tasks.Count > 0 ? tasks.Average(t => t.CompletionRate) : 0,
                    TotalPlannedQty = tasks.Sum(t => t.PlannedQty),
                    TotalQualifiedQty = tasks.Sum(t => t.QualifiedQty),
                    TotalUnqualifiedQty = tasks.Sum(t => t.UnqualifiedQty)
                };

                return new APIResult<object>
                {
                    Code = APIEnums.Success,
                    Msg = "获取看板任务统计成功",
                    Data = statistics
                };
            }
            catch (Exception ex)
            {
                return new APIResult<object>
                {
                    Code = APIEnums.Error,
                    Msg = $"获取看板任务统计失败: {ex.Message}",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 获取产品报工统计数据（用于大屏图表展示）
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>统计结果：总报工量、合格率趋势等</returns>
        /// <response code="200">查询成功</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet]
        [ProducesResponseType(typeof(APIResult<object>), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<APIResult<object>> GetProductionDashboardStatistics(CancellationToken cancellationToken)
        {
            try
            {
                // 获取所有产品报工数据（不分页）用于统计
                var allReportsRequest = new GetProductionDashboardPageCommand
                {
                    PageIndex = 1,
                    PageSize = int.MaxValue // 获取全部数据用于统计
                };

                var allReportsResult = await mediator.Send(allReportsRequest, cancellationToken);

                if (allReportsResult.Code != APIEnums.Success)
                {
                    return new APIResult<object>
                    {
                        Code = APIEnums.Error,
                        Msg = "获取产品报工统计失败",
                        Data = null
                    };
                }

                var reports = allReportsResult.PageDatas ?? new List<ProductionDashboardListDto>();

                var statistics = new
                {
                    TotalReports = reports.Count,
                    TotalReportQty = reports.Sum(r => r.ReportQty),
                    TotalQualifiedQty = reports.Sum(r => r.QualifiedQty),
                    AvgPassRate = reports.Count > 0 ? reports.Average(r => r.PassRate) : 0,
                    ProductCounts = reports.GroupBy(r => r.ProductName)
                                          .ToDictionary(g => g.Key, g => new
                                          {
                                              Count = g.Count(),
                                              TotalQty = g.Sum(x => x.ReportQty),
                                              QualifiedQty = g.Sum(x => x.QualifiedQty)
                                          }),
                    DailyTrend = reports.GroupBy(r => r.ReportTime.Date)
                                       .OrderBy(g => g.Key)
                                       .Select(g => new
                                       {
                                           Date = g.Key.ToString("yyyy-MM-dd"),
                                           ReportQty = g.Sum(x => x.ReportQty),
                                           QualifiedQty = g.Sum(x => x.QualifiedQty),
                                           PassRate = g.Sum(x => x.ReportQty) > 0 ?
                                                     (double)g.Sum(x => x.QualifiedQty) / g.Sum(x => x.ReportQty) : 0
                                       })
                                       .ToList()
                };

                return new APIResult<object>
                {
                    Code = APIEnums.Success,
                    Msg = "获取产品报工统计成功",
                    Data = statistics
                };
            }
            catch (Exception ex)
            {
                return new APIResult<object>
                {
                    Code = APIEnums.Error,
                    Msg = $"获取产品报工统计失败: {ex.Message}",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 本月概览统计（卡片：本月收入、本月订单、今日回款、本月采购、本月发货、库存金额）
        /// </summary>
        /// <param name="request">可选：Month 指定月份，默认当前月</param>
        /// <param name="cancellationToken"></param>
        [HttpGet]
        [ProducesResponseType(typeof(APIResult<MonthlyOverviewDto>), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<APIResult<MonthlyOverviewDto>> GetMonthlyOverview([FromQuery] GetMonthlyOverviewCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = await mediator.Send(request ?? new GetMonthlyOverviewCommand(), cancellationToken);
                return result;
            }
            catch (Exception ex)
            {
                return new APIResult<MonthlyOverviewDto>
                {
                    Code = APIEnums.Error,
                    Msg = $"获取本月概览统计失败: {ex.Message}"
                };
            }
        }
    }
}
